//
//  UIViewController+Keyboard.m
//
//  Created by 赵梁 on 8/28/15.
//  Copyright (c) 2015 zify. All rights reserved.
//

#import "UIViewController+Keyboard.h"

#import <objc/runtime.h>

static char key_keboardCompletionBlock;

typedef void (^CompletionBlock)();

@implementation UIViewController(Keyboard)


#pragma mark - 点击屏幕任何地方隐藏键盘实现
- (void)setUpForDismissKeyboardWithCompletionBlock:(void (^)())completionBlock
{
    [self setCompletionBlock:completionBlock];
    [self setUpForDismissKeyboard];
}

- (void)setUpForDismissKeyboard
{
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    UITapGestureRecognizer *singleTapGR =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAnywhereToDismissKeyboard:)];
    NSOperationQueue *mainQuene =[NSOperationQueue mainQueue];
    [nc addObserverForName:UIKeyboardWillShowNotification object:nil queue:mainQuene usingBlock:^(NSNotification *note){
        [self.view addGestureRecognizer:singleTapGR];
    }];
    [nc addObserverForName:UIKeyboardWillHideNotification object:nil queue:mainQuene usingBlock:^(NSNotification *note){
        [self.view removeGestureRecognizer:singleTapGR];
    }];
}

- (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer
{
    CompletionBlock completionBlock = [self completionBlock];
    if (completionBlock) {
        completionBlock();
    }
    [self hiddenAllKeyboard];
}

/**
 *  关闭键盘
 */
-(void)hiddenAllKeyboard
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}

#pragma mark - block
- (void)setCompletionBlock:(CompletionBlock) completionBlock
{
    objc_setAssociatedObject(self, &key_keboardCompletionBlock, completionBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (CompletionBlock)completionBlock
{
    return objc_getAssociatedObject(self, &key_keboardCompletionBlock);
}

@end
